import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { useAuthModalStore } from '@/stores/authModal'
import { useLoadingStore } from '@/stores/loading'

const routes = [
  // 认证相关路由 - 新的分离式登录系统
  // 注意：旧的登录入口已迁移，新的入口：/auth (选择页面)
  {
    path: '/auth',
    name: 'Auth',
    component: () => import('@/layouts/AuthLayout.vue'),
    children: [
      {
        path: '',
        name: 'LoginChoice',
        component: () => import('@/views/auth/LoginChoice.vue'),
        meta: { title: '选择登录方式', guest: true },
      },
      {
        path: 'login',
        name: 'Login',
        component: () => import('@/views/auth/Login.vue'),
        meta: { title: '用户登录', guest: true },
      },
      {
        path: 'admin-login',
        name: 'AdminLogin',
        component: () => import('@/views/auth/AdminLogin.vue'),
        meta: { title: '管理员登录', guest: true },
      },
      {
        path: 'register',
        name: 'Register',
        component: () => import('@/views/auth/Register.vue'),
        meta: { title: '注册', guest: true },
      },
      {
        path: 'forgot-password',
        name: 'ForgotPassword',
        component: () => import('@/views/auth/ForgotPassword.vue'),
        meta: { title: '忘记密码', guest: true },
      },
    ],
  },

  // 主布局路由
  {
    path: '/',
    name: 'Layout',
    component: () => import('@/layouts/MainLayout.vue'),
    children: [
      // 首页
      {
        path: '',
        name: 'Home',
        component: () => import('@/views/home/Home.vue'),
        meta: { title: '首页' },
      },
      // 静态信息页面
      {
        path: '/about',
        name: 'About',
        component: () => import('@/views/AboutView.vue'),
        meta: { title: '关于我们' },
      },
      {
        path: '/contact',
        name: 'Contact',
        component: () => import('@/views/Contact.vue'),
        meta: { title: '联系我们' },
      },
      {
        path: '/jobs',
        name: 'Jobs',
        component: () => import('@/views/Jobs.vue'),
        meta: { title: '加入我们' },
      },
      {
        path: '/service',
        name: 'Service',
        component: () => import('@/views/Service.vue'),
        meta: { title: '售后服务' },
      },
      {
        path: '/shipping',
        name: 'Shipping',
        component: () => import('@/views/Shipping.vue'),
        meta: { title: '配送方式' },
      },
      {
        path: '/returns',
        name: 'Returns',
        component: () => import('@/views/Returns.vue'),
        meta: { title: '退换货' },
      },
      {
        path: '/feedback',
        name: 'Feedback',
        component: () => import('@/views/Feedback.vue'),
        meta: { title: '意见反馈' },
      },
      {
        path: '/help',
        name: 'Help',
        component: () => import('@/views/Help.vue'),
        meta: { title: '购物帮助' },
      },
      {
        path: '/test-stepin',
        name: 'TestStepin',
        component: () => import('@/views/TestStepin.vue'),
        meta: { title: 'Stepin转场测试' },
      },
      {
        path: '/test-image-manager',
        name: 'TestImageManager',
        component: () => import('@/views/TestImageManager.vue'),
        meta: { title: '图片管理测试' },
      },

      // 商品相关路由
      {
        path: '/products',
        name: 'Products',
        component: () => import('@/views/product/ProductList.vue'),
        meta: { title: '商品列表' },
      },
      {
        path: '/categories',
        name: 'Categories',
        component: () => import('@/views/product/Categories.vue'),
        meta: { title: '全部分类' },
      },
      {
        path: '/brands',
        name: 'Brands',
        component: () => import('@/views/product/Brands.vue'),
        meta: { title: '品牌' },
      },
      {
        path: '/product/:id',
        name: 'ProductDetail',
        component: () => import('@/views/product/ProductDetail.vue'),
        meta: { title: '商品详情' },
        props: true,
      },
      {
        path: '/category/:id',
        name: 'CategoryProducts',
        component: () => import('@/views/product/CategoryProducts.vue'),
        meta: { title: '分类商品' },
        props: true,
      },
      {
        path: '/brand/:id',
        name: 'BrandProducts',
        component: () => import('@/views/product/BrandProducts.vue'),
        meta: { title: '品牌商品' },
        props: true,
      },
      {
        path: '/search',
        name: 'Search',
        component: () => import('@/views/product/SearchResults.vue'),
        meta: { title: '搜索结果' },
      },

      // 购物车路由
      {
        path: '/cart',
        name: 'Cart',
        component: () => import('@/views/cart/Cart.vue'),
        meta: { title: '购物车', requiresAuth: true },
      },

      // 订单相关路由
      {
        path: '/orders',
        name: 'Orders',
        component: () => import('@/views/order/OrderList.vue'),
        meta: { title: '我的订单', requiresAuth: true },
      },
      {
        path: '/order/:id',
        name: 'OrderDetail',
        component: () => import('@/views/order/OrderDetail.vue'),
        meta: { title: '订单详情', requiresAuth: true },
        props: true,
      },
      {
        path: '/order/:id/review',
        name: 'OrderReview',
        component: () => import('@/views/order/OrderReview.vue'),
        meta: { title: '订单评价', requiresAuth: true },
        props: true,
      },
      {
        path: '/checkout',
        name: 'Checkout',
        component: () => import('@/views/order/Checkout.vue'),
        meta: { title: '结算', requiresAuth: true },
      },

      // 用户中心路由
      {
        path: '/user',
        name: 'UserCenter',
        component: () => import('@/views/user/UserCenter.vue'),
        meta: { title: '个人中心', requiresAuth: true },
        children: [
          {
            path: '',
            name: 'UserDefault',
            redirect: () => {
              if (typeof window !== 'undefined') {
                const saved = localStorage.getItem('userCenter.activeMenu')
                if (saved) return `/user/${saved}`
              }
              return '/user/profile'
            }
          },
          {
            path: 'profile',
            name: 'UserProfile',
            component: () => import('@/views/user/Profile.vue'),
            meta: { title: '个人信息' },
          },
          {
            path: 'address',
            name: 'UserAddress',
            component: () => import('@/views/user/Address.vue'),
            meta: { title: '收货地址' },
          },
          {
            path: 'orders',
            name: 'UserOrders',
            component: () => import('@/views/user/Order.vue'),
            meta: { title: '我的订单' },
          },
          {
            path: 'wishlist',
            name: 'UserWishlist',
            component: () => import('@/views/user/Wishlist.vue'),
            meta: { title: '我的收藏' },
          },
          {
            path: 'coupon',
            name: 'UserCoupon',
            component: () => import('@/views/user/Coupon.vue'),
            meta: { title: '优惠券' },
          },
          {
            path: 'security',
            name: 'UserSecurity',
            component: () => import('@/views/user/Security.vue'),
            meta: { title: '账户安全' },
          },
        ],
      },

      // 支付相关路由
      {
        path: '/payment/:orderId?',
        name: 'Payment',
        component: () => import('@/views/payment/Payment.vue'),
        meta: { title: '支付', requiresAuth: true },
        props: (route: any) => ({
          orderId: route.params.orderId || route.query.orderId
        }),
      },
      {
        path: '/payment/success',
        name: 'PaymentSuccess',
        component: () => import('@/views/payment/Success.vue'),
        meta: { title: '支付成功', requiresAuth: true },
      },
      {
        path: '/payment/failed',
        name: 'PaymentFailed',
        component: () => import('@/views/payment/Failed.vue'),
        meta: { title: '支付失败', requiresAuth: true },
      },
    ],
  },

  // 管理员路由
  {
    path: '/admin',
    name: 'Admin',
    component: () => import('@/layouts/AdminLayout.vue'),
    meta: { requiresAuth: true, requiresAdmin: true },
    children: [
      {
        path: '',
        name: 'AdminDashboard',
        component: () => import('@/views/admin/Dashboard.vue'),
        meta: { title: '管理后台' },
      },
      {
        path: 'products',
        name: 'AdminProducts',
        component: () => import('@/views/admin/ProductManage.vue'),
        meta: { title: '商品管理' },
      },
      {
        path: 'products/add',
        name: 'AdminProductAdd',
        component: () => import('@/views/admin/ProductEdit.vue'),
        meta: { title: '新增商品' },
      },
      {
        path: 'products/:id/edit',
        name: 'AdminProductEdit',
        component: () => import('@/views/admin/ProductEdit.vue'),
        meta: { title: '编辑商品' },
        props: true,
      },
      {
        path: 'orders',
        name: 'AdminOrders',
        component: () => import('@/views/admin/OrderManage.vue'),
        meta: { title: '订单管理' },
      },
      {
        path: 'users',
        name: 'AdminUsers',
        component: () => import('@/views/admin/UserManage.vue'),
        meta: { title: '用户管理' },
      },
      {
        path: 'categories',
        name: 'AdminCategories',
        component: () => import('@/views/admin/CategoryManage.vue'),
        meta: { title: '分类管理' },
      },
      {
        path: 'brands',
        name: 'AdminBrands',
        component: () => import('@/views/admin/BrandManage.vue'),
        meta: { title: '品牌管理' },
      },
      {
        path: 'advertisements',
        name: 'AdminAdvertisements',
        component: () => import('@/views/admin/AdvertisementManage.vue'),
        meta: { title: '广告管理' },
      },
      {
        path: 'partner-links',
        name: 'AdminPartnerLinks',
        component: () => import('@/views/admin/PartnerLinkManage.vue'),
        meta: { title: '友链管理' },
      },
      {
        path: 'colors',
        name: 'AdminColors',
        component: () => import('@/views/admin/ColorManage.vue'),
        meta: { title: '颜色管理' },
      },
      {
        path: 'sizes',
        name: 'AdminSizes',
        component: () => import('@/views/admin/SizeManage.vue'),
        meta: { title: '尺码管理' },
      },
      {
        path: 'stock',
        name: 'AdminStock',
        component: () => import('@/views/admin/StockManage.vue'),
        meta: { title: '库存管理' },
      },
      {
        path: 'reports/traffic',
        name: 'AdminReportTraffic',
        component: () => import('@/views/admin/TrafficReport.vue'),
        meta: { title: '流量报表' },
      },
      {
        path: 'reports/marketing',
        name: 'AdminReportMarketing',
        component: () => import('@/views/admin/MarketingReport.vue'),
        meta: { title: '营销报表' },
      },
      {
        path: 'reports/performance',
        name: 'AdminReportPerformance',
        component: () => import('@/views/admin/PerformanceReport.vue'),
        meta: { title: '业绩报表' },
      },
      {
        path: 'admins',
        name: 'AdminManage',
        component: () => import('@/views/admin/AdminManage.vue'),
        meta: { title: '管理员管理', requiresSuperAdmin: true },
      },
    ],
  },

  // 404页面
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/error/404.vue'),
    meta: { title: '页面不存在' },
  },
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
  scrollBehavior() {
    return { top: 0 }
  },
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore()
  
  // 显示路由加载动画
  const loadingStore = useLoadingStore()
  loadingStore.showRouteLoading()

  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - 鞋类在线购物平台`
  }

  // 检测是否为移动端
  const isMobile = window.innerWidth <= 768

  // 需要管理员权限的路由：优先单独处理
  if (to.meta.requiresAdmin) {
    if (!authStore.isLoggedIn || !authStore.isAdmin) {
      next({ name: 'AdminLogin', query: { redirect: to.fullPath } })
      return
    }
  }

  // 需要认证（普通用户）
  if (to.meta.requiresAuth && !to.meta.requiresAdmin) {
    if (!authStore.isLoggedIn) {
      if (isMobile) {
        // 移动端：直接重定向到登录页面
        next({ name: 'Login', query: { redirect: to.fullPath } })
      } else {
        // 桌面端：弹窗提示
        const authModal = useAuthModalStore()
        authModal.openLogin(to.fullPath, '请先登录以继续')
        next(false)
      }
      return
    }
  }

  // 不允许已登录用户访问的路由
  if (to.meta.guest && authStore.isLoggedIn) {
    next({ name: 'Home' })
    return
  }

  next()
})

// 路由切换完成后隐藏加载动画
router.afterEach((to, from) => {
  const loadingStore = useLoadingStore()
  // 延迟一点时间确保页面内容加载完成
  setTimeout(() => {
    loadingStore.hideRouteLoading()
  }, 300)
})

export default router
